<?php
namespace Admin\Controller;

class TeacherController extends AdminController {
    public function index(){
    	$this->assign('schoolList', R('Common/getSchoolList'));
    	//定义搜索项
    	$searchItems = array(
    		array('select', 'school_id', '所属学校', 'schoolList'),
    		array('input' ,'username', '用户名'),
    	);
    	$this->assign('searchItems', $searchItems);
    	
    	$map = array();
    	$schoolId = I('school_id');
    	$username = I('username');
    	if ($schoolId > 0) {
    		$map['school_id'] = $schoolId;
    	}
    	if (!empty($username)) {
    		$map['username'] = $username;
    	}
    	$list   = $this->lists('Teacher', $map);
        $this->assign('_list', $list);
        $this->meta_title = '教师列表';
        $this->display();
    }
    
    public function gen(){
    	$this->assign('schoolList', R('Common/getSchoolList'));
    	$this->meta_title = '生成教师账号';
    	$this->display();
    }

    public function doGen(){
    	if (IS_POST) {
    		$model = D('Teacher');
    		$schoolId = I('post.school_id');
    		if ($schoolId == 0) {
    			$this->error('请先选择学校');
    		}
    		$lists = $model->where(array('school_id' => $schoolId))->field('username')->select();
    		$alreadyUsers = array_column($lists, 'username');
    		$string = I('post.usernames');
    		$array = preg_split('/[\r\n]+/', trim($string, ",;\r\n"));
    		if (!empty($array)) {
    			$data = array();
    			foreach ($array as $username){
    				if (in_array($username, $alreadyUsers)) {//判断其中某些是否已经添加过
    					continue;
    				}
    				$item = array();
    				$item['username'] 	= $username;
    				$item['password'] 	= create_password(6);
    				$item['school_id']	= $schoolId;
    				$data[] = $item;
    			}
    			if ($model->addAll($data)) {
    				$this->success('生成成功', U('index'));
    			}
    		}else {
    			$this->error('请输入用户名');
    		}
    	}
    }
    
    public function del(){
    	$id = I('get.id');
    	$id = intval($id);
    	$ret = D('Teacher')->where(array('id' => $id))->delete();
    	if ($ret !== false) {
    		$this->success('删除成功');
    	}
    }
}